package com.server.common.security.code.utils;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil;
import com.server.model.all.constant.PatternConstant;
import org.springframework.util.ObjectUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MapperAnnotationUtils {


    /**
     * 获取参数
     * @author LXC
     * @date 2022/6/8 21:26
     */
    public static  <T extends Annotation> List<String> getRequestMappingValue(Method method) {
        Annotation[] annotations = method.getAnnotations();

        Annotation annotation = Arrays.stream(annotations)
                .filter(a -> {
                    Matcher matcher = Pattern.compile(PatternConstant.REQUEST_MAPPING).matcher(a.annotationType().getName());
                    return matcher.matches();
                })
                .findFirst()
                .orElse(null);
        if(ObjectUtils.isEmpty(annotation)){
            return null;
        }
        Method value = ReflectUtil.getMethod(ClassUtil.loadClass(annotation.annotationType().getName()), "value");
        value.setAccessible(true);
        return Optional.of(Arrays.asList((String[])ReflectUtil.invoke(annotation, value))).orElse(Collections.emptyList());
    }

}
